﻿
using UnityEngine;
using UnityEngine.Playables;
using UnityEngine.UI;

public class TextSwitcherMixerBehaviour : PlayableBehaviour {
    private Color  _defaultColor;
    private int    _defaultFontSize;
    private string _defaultText;
    private float  _currentAlpha;
 
    private Text _trackBinding;
 
    public override void ProcessFrame(Playable playable, FrameData info, object playerData) {
        _trackBinding = playerData as Text;
 
        _defaultText  = "";
        _currentAlpha = 0f;
 
        if(!_trackBinding){ return; }
 
        int inputCount = playable.GetInputCount();
 
        for(int i = 0; i < inputCount; i++){
            float inputWeight = playable.GetInputWeight(i);
            if(inputWeight > 0f){
                ScriptPlayable<TextSwitcherBehaviour> inputPlayable =
                    (ScriptPlayable<TextSwitcherBehaviour>) playable.GetInput(i);
                TextSwitcherBehaviour input = inputPlayable.GetBehaviour();
                _defaultText     = input.text;
                _defaultFontSize = input.fontSize;
                _defaultColor    = input.color;
                _currentAlpha    = inputWeight;
 
                _defaultColor.a = _currentAlpha;
            }
        }
 
        _trackBinding.text     = _defaultText;
        _trackBinding.fontSize = _defaultFontSize;
        _trackBinding.color    = _defaultColor;
    }
 
    public override void OnPlayableDestroy(Playable playable) {
        if(_trackBinding == null){ return; }
 
        _trackBinding.color    = _defaultColor;
        _trackBinding.fontSize = _defaultFontSize;
        _trackBinding.text     = _defaultText;
    }
}